//app.js

//require("./api/index")
var awx = require("./utils/awx")
var utils = require("./utils/util");
var config = require("./config");
const api = require("./utils/api");
var serverUrl = config.HTTP_REQUEST_URL;
var o = config.HTTP_REQUEST_URL;
var e = config.DEFAULT_PAGE_URL;
var i = config.AUTHORIZE_PAGE_URL;
var l = o;
var music = wx.createInnerAudioContext();

App({
  onLaunch: function () {
    this.init();
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        env: 'autoluhu-4grd0xd2584a8220',
        traceUser: true,
      })
    }
    if (wx.getStorageSync('playMusic') !== '') {
      this.globalData.playMusic = wx.getStorageSync('playMusic') ? 1 : 0;
    }
  },

  onReady: function () {
    wx.redirectTo({
      url: '/pages/home/index/index',
    });
  },

  globalData: {
    baseUrl: serverUrl,
    imageUrl: serverUrl + "/images/wxapp",
    share: {
      title: "云撞钟  共祈福",
      path: "/pages/home/index/index",
      imageUrl: serverUrl + "/images/wxapp/home/index/bg1.jpg"
    },
    uploadImg: [],
    uploadImages: [],
    token: "",
    isIPhoneX: 0,
    isSmallPhone: 0,
    playMusic: 1,
    music: null,
    time: "",
    blessActivityId: "",
  },

  init: function () {
    var self = this;
    music.src = "https://newyear.fosiyun.com/audio/music.mp3";
    music.autoplay = 1;
    music.loop = 1;
    this.globalData.music = music;
    music.onEnded(function () {
        music.startTime = 0, music.play(), music.title = "bgm";
      }),
      music.onPlay(function () {
        return self.globalData.playMusic = !0;
      });
    music.onPause(function () {
      return self.globalData.playMusic = !1;
    });
    wx.getSystemInfo({
      success: function (n) {
        var o = n.model;
        if (-1 != o.indexOf("iPhone X") || -1 != o.indexOf("iPhone 11") || -1 != o.indexOf("iPhone 12") || -1 != o.indexOf("iPhone 13") || -1 != o.indexOf("iPhone14")) {
          self.globalData.isIPhoneX = 1;
        } else {
          self.globalData.isIPhoneX = 0;
        }
        var height = utils.$h.Mul(utils.$h.Div(750, n.windowWidth), n.windowHeight);
        if (height <= 1440) {
          self.globalData.isSmallPhone = true;
        } else {
          self.globalData.isSmallPhone = false;
        }
        console.log("机型: " + n.model);
        console.log("屏幕高度: " + height);
        console.log("是否为小机型: " + self.globalData.isSmallPhone);
        console.log("baseUrl: " + self.globalData.baseUrl);
        console.log("imageUrl: " + self.globalData.imageUrl);
        console.log("token: " + (self.globalData.token || "暂无token"));
        console.log("isIPhoneX: " + self.globalData.isIPhoneX);
      }
    });
    var token = wx.getStorageSync("token");
    this.globalData.token = token;
    var updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (n) {});
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: "更新提示",
        content: "新版本已经准备好，是否重启应用？",
        success: function (n) {
          n.confirm && u.applyUpdate();
        }
      });
    });
    updateManager.onUpdateFailed(function () {
      return t.text("新版本下载失败");
    });
  },

  success: function (n, a, t) {
    wx.showToast({
      title: n,
      icon: "success",
      duration: a || 2e3,
      success: function (n) {
        t && t(n);
      }
    });
  },

  error: function (n, a, t) {
    wx.showToast({
      title: n,
      image: "/images/alert.png",
      duration: a || 2e3,
      success: function (n) {
        t && t(n);
      }
    });
  },

  text: function (title, dur, fn) {
    wx.showToast({
      title: title,
      icon: "none",
      duration: dur || 2e3,
      success: function (res) {
        fn && fn(res);
      }
    });
  },

  showModal: function (n, a) {
    var t = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : "提示";
    wx.showModal({
      title: t,
      content: n,
      showCancel: !1,
      success: function () {
        a && a();
      }
    });
  },

  showMessage: function (n, a, t) {
    wx.showModal({
      title: "提示",
      content: n,
      success: function (n) {
        n.confirm ? a && a() : n.cancel && t && t();
      },
      fail: function () {
        t && t();
      }
    });
  },

  showLoading: function (n, a) {
    wx.showLoading({
      title: n || "加载中",
      mask: !0,
      complete: a && a()
    });
  },

  hideLoading: function () {
    wx.hideLoading();
  },

  switchTab: function (n) {
    if (!n) return wx.showModal({
      title: "参数错误",
      content: "没有传跳转的页面路径",
      showCancel: !1
    }), !1;
    wx.showLoading(), setTimeout(function () {
      wx.hideLoading();
    }, 1e3), wx.switchTab({
      url: n || ""
    });
  },

  reLaunch: function (n) {
    if (!n) return wx.showModal({
      title: "参数错误",
      content: "没有传跳转的页面路径",
      showCancel: !1
    }), !1;
    wx.showLoading(), setTimeout(function () {
      wx.hideLoading();
    }, 1e3), wx.reLaunch({
      url: n || ""
    });
  },

  redirectTo: function (n) {
    if (!n) return wx.showModal({
      title: "参数错误",
      content: "没有传跳转的页面路径",
      showCancel: !1
    }), !1;
    wx.showLoading(), setTimeout(function () {
      wx.hideLoading();
    }, 1e3), wx.redirectTo({
      url: n || ""
    });
  },

  navigateTo: function (n) {
    if (!n) return wx.showModal({
      title: "参数错误",
      content: "没有传跳转的页面路径",
      showCancel: !1
    }), !1;
    wx.showLoading(), setTimeout(function () {
      wx.hideLoading();
    }, 1e3), wx.navigateTo({
      url: n || ""
    });
  },

  navigateBack: function (n) {
    wx.showLoading(), setTimeout(function () {
      wx.hideLoading();
    }, 1e3), wx.navigateBack({
      delta: n || 1
    });
  },

  showImage: function (n, a) {
    wx.previewImage({
      current: n,
      urls: a
    });
  },

  getOnload: function (mod) {
    mod.setData({
      imageUrl: this.globalData.imageUrl
    });
  },

  checkLogin: async function (mod) {
    console.log('checkLogin');
    console.log(awx);
    try {
      let settingRes = await awx.getSetting();
      console.log(settingRes);
      if (!settingRes.authSetting['scope.userInfo']) {
        return Promise.reject('请授权获取您的信息');
      }
      console.log('授权成功');
      let userInfoRes = await awx.getUserInfo();
      mod.setData({
        avatarUrl: userInfoRes.userInfo.avatarUrl,
        userInfo: userInfoRes.userInfo
      });
      console.log('login');
      api.login().then(loginResult => {
        console.log(loginResult);
        if (loginResult.code == 0) {
          return Promise.resolve('success');
        } else {
          return Promise.reject('failed');
        }
      }).catch(err => {
        return Promise.reject('failed');
      });
    } catch (err) {
      console.log('login catch exception, err=' + err);
      return Promise.reject('exception ' + err);
    };
  },

  getToken: function (a) {
    var t = this.globalData.token;
    return new Promise(function (o, e) {
      t ? (a.setData(n({}, "authParams.authModal", !1)), o()) : a.setData(n({}, "authParams.authModal", !0));
    });
  },

  getOnShow: function () {},

  dateFormat: function (n) {
    var a, t, o, e;
    !(n = "string" == typeof n ? parseInt(n) : n) || n < 0 || (a = n / 86400 | 0, t = (n = Math.round(n) - 24 * a * 3600) / 3600 | 0,
      o = (n = Math.round(n) - 3600 * t) / 60 | 0, e = Math.round(n) - 60 * o, Math.round(a) < 10 && (a = a > 0 ? "0" + a : ""),
      Math.round(t) < 10 && (t = "0" + t), Math.round(o) < 10 && (o = "0" + o), Math.round(e) < 10 && (e = "0" + e),
      this.globalData.time = t + ":" + o + ":" + e);
  },

  uploadimg: function (n, a, t) {
    o = this;
    t = t || {};
    var o = this,
      e = n.i ? n.i : 0,
      i = n.success ? n.success : 0,
      l = n.fail ? n.fail : 0;
    wx.uploadFile({
      url: o.globalData.baseUrl + "/" + n.url,
      filePath: n.path[e].path,
      name: "file",
      formData: t,
      header: {
        "Content-Type": "multipart/form-data",
        token: o.globalData.token
      },
      success: function (n) {
        i++;
      },
      fail: function (n) {
        l++;
      },
      complete: function (s) {
        if (500 != s.statusCode)
          if (s = JSON.parse(s.data), console.log(s), ++e == n.path.length)
            if (o.globalData.uploadImg.push(s.d.id),
              o.globalData.uploadImages.push(s.d), n.path[0].cover) {
              var u = n.path[0].cover;
              console.log("有封面图,开始上传封面图"), o.uploadimg({
                i: 0,
                url: n.url,
                path: [{
                  path: u
                }]
              }, a, {
                type: 1
              });
            } else n.upload && a ? 1 == n.path.length && a([s.d]) : a(o.globalData.uploadImg),
              o.globalData.uploadImg = [], o.globalData.uploadImages = [];
        else n.i = e, n.success = i,
          n.fail = l, o.globalData.uploadImg.push(s.d.id), o.globalData.uploadImages.push(s.d),
          o.uploadimg(n, a, t);
        else o.text("系统出现故障，请稍后再试~");
      }
    });
  },

  initMod: function (mod) {
    mod.setData({
      playMusic: this.globalData.playMusic,
    });
    if (mod.data.playMusic) {
      this.globalData.music.play();
    } else {
      this.globalData.music.pause();
    }
  },

  playMusic: function (mod, e) {
    var t = mod.data.playMusic;
    mod.setData({
      playMusic: !t
    });
    if (t) {
      console.log('pause');
      this.globalData.music.pause();
    } else {
      console.log('play');
      this.globalData.music.play();
    }
    wx.setStorageSync('playMusic', mod.data.playMusic);
  },

});